package m.jclecai.com.fragment.home;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.LayoutRes;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import m.jclecai.com.R;
import m.jclecai.com.activity.WebLoadRichTextActivity;
import m.jclecai.com.adapter.base.ViewHolerAdapter;
import m.jclecai.com.adapter.holder.ViewHolder;
import m.jclecai.com.base.BaseFragment;
import m.jclecai.com.bean.home.Entires;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.contents.NotificationKey;
import m.jclecai.com.data.Lecai_SDK;
import m.jclecai.com.data.ReceivedData;
import m.jclecai.com.notification.NotificationCenter;
import m.jclecai.com.notification.NotificationListener;
import m.jclecai.com.utils.StrUtils;
import m.jclecai.com.utils.http.HttpManager;

/**
 * Created by andy on 2017/7/21.
 * <p>
 *  足球新闻开关也面
 */

public class HomeSwitchItemFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListener2 ,NotificationListener{

    @BindView(R.id.prl_list_view)
    PullToRefreshListView mPrlListView;

    private int mPosition = 0;
    List<Entires> list=new ArrayList<>();
    private MyAdapter mMyAdapter;
    private int page = 1;
    private String content = "";
    private long id = 0;
    private ReceivedData.HomeMenusDetailData homeMenusDetailData = null;

    public void setPosition(int position) {
        mPosition = position;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_news;
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 12345678:
                    startActivity(WebLoadRichTextActivity.getInstance(getActivity(),homeMenusDetailData.data.content,false,"新闻详情"));
                    break;
            }
        }
    };
    @Override
    public void initData() {
        super.initData();
        NotificationCenter.defaultCenter.addListener(NotificationKey.FmLoadData, this);
        mMyAdapter = new MyAdapter(list);
        mPrlListView.setAdapter(mMyAdapter);
        mPrlListView.setOnRefreshListener(this);
        mPrlListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                 Lecai_SDK.web_title = list.get(position-1).getName();
                 Lecai_SDK.web_type  = list.get(position-1).tagKey;
                 requestData(Constant_Url.MENNU_CHILD_DETIL_TAG,list.get(position-1).getPostId());
//                String url= "http://m.yuecp.nt/view/index.html?id="+list.get(position).getPostId();
            }
        });

        mPrlListView.refreshDrawableState();

    }

    String url="";
    /**
     * 请求数据；
     */
    public void requestData(final int tag,long id) {
        this.id = id;
        if (tag == Constant_Url.MENNU_CHILD_TITLE_TAG){
            String type = "0,1,2,3,4,5,6";
            type = TransCode(type);
            url= Constant_Url.MENNU_CHILD_TITLE+"&type="+type+"&relatedId="+id+"&page="+page;
        }else if (tag == Constant_Url.MENNU_CHILD_DETIL_TAG){
            url= Constant_Url.MENNU_CHILD_DETIL+id+"?caller=1003";
        }
        HttpManager.getAsyn(url, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlay("网络异常！！！");
                if (mPrlListView != null) {
                    mPrlListView.onRefreshComplete();
                }
            }

            @Override
            public void onResponse(String response) {
                if (mPrlListView != null) {
                    mPrlListView.onRefreshComplete();
                }
                if(!TextUtils.isEmpty(response)){
                    Gson gson = new Gson();
                    if (tag == Constant_Url.MENNU_CHILD_TITLE_TAG){
                        Log.e("==tag==",response);
                        ReceivedData.HomeMenusItemData homeMenusItemData =
                                gson.fromJson(response, ReceivedData.HomeMenusItemData.class);
                        List<Entires> entires = homeMenusItemData.data.getEntries();

                        if (homeMenusItemData.code==200) {
                            setData(entires);
                        }else{
                            DisPlay(homeMenusItemData.msg);
                        }
                    }else if (tag == Constant_Url.MENNU_CHILD_DETIL_TAG){
                        if(response != null && response.startsWith("\ufeff"))
                        {
                            response =  response.substring(1);
                        }
                        homeMenusDetailData =
                                gson.fromJson(response, ReceivedData.HomeMenusDetailData.class);
                        Message msg = new Message();
                        msg.what = 12345678;
                        handler.sendMessage(msg);
                    }
                }else{
                    //这里表示返回为空；
                    DisPlay("网络异常！！！");
                }

            }
        });
    }



    private String TransCode(String url){
        String strUTF8 = "";
        try {
            strUTF8 = URLEncoder.encode(url, "UTF-8");//转码
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return strUTF8;
    }

    public void setData(List<Entires> bean) {
        if(page==1){
            mMyAdapter.refresh(bean);
        }else{
            mMyAdapter.addData(bean);
        }
        page = page+1;



    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        //下拉刷新；
        page=1;
        mMyAdapter.clear();
        requestData(Constant_Url.MENNU_CHILD_TITLE_TAG,id);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        requestData(Constant_Url.MENNU_CHILD_TITLE_TAG,id);
    }

    @Override
    public boolean onNotification(Notification notification) {
        if (notification.key.equals(NotificationKey.FmLoadData)) {
            requestData(Constant_Url.MENNU_CHILD_TITLE_TAG,Lecai_SDK.title_id);
        }
        return  true;
    }


    public class MyAdapter extends ViewHolerAdapter<NewsViewHolder> {

        public MyAdapter(List<Entires>  newsBeanList) {
            mNewsBeanList = newsBeanList;
        }

        List<Entires>  mNewsBeanList;


        @Override
        public NewsViewHolder onCreateViewHolder(int position, ViewGroup parent) {
            return new NewsViewHolder(getContext(), R.layout.item_list_menus);
        }

        @Override
        public void onBindViewHolder(int position, NewsViewHolder myViewHolder) {
            Entires newsBean = mNewsBeanList.get(position);
            Object imageUrl = newsBean.imageUrl;
            if (null!=imageUrl){
                String StrPic = newsBean.imageUrl.toString();
                String[] split = StrPic.split(",");
                if (null!=split&&split.length>0){
                    for (int i = 0; i < split.length; i++) {
                        if (split[0].length()>7){
                            Glide.with(getContext()).load(StrUtils.SubString(split[0])).into(myViewHolder.mIvNewsLogo);
                        }
                    }
                }

            }


            myViewHolder.mTvContent.setText(newsBean.getName());
            myViewHolder.mTvTitle.setText(newsBean.getName());
            myViewHolder.mTvDate.setText(newsBean.tagKey);

            myViewHolder.mTvIsStart.setVisibility(View.INVISIBLE);
        }

        @Override
        public int getCount() {
            return mNewsBeanList.size();
        }

        public List<Entires>   getNewsBeanList(){
            return mNewsBeanList;
        }


        public void refresh(List<Entires> data) {
            mNewsBeanList.clear();
            mNewsBeanList.addAll(data);
            notifyDataSetChanged();
        }
        public void clear(){
            mNewsBeanList.clear();
            notifyDataSetChanged();
        }

        public void addData(List<Entires> data){
            mNewsBeanList.addAll(data);
            notifyDataSetChanged();
        }

    }

    public class NewsViewHolder extends ViewHolder {

        @BindView(R.id.iv_news_logo)
        ImageView mIvNewsLogo;
        @BindView(R.id.tv_title)
        TextView mTvTitle;
        @BindView(R.id.tv_is_start)
        TextView mTvIsStart;
        @BindView(R.id.tv_date)
        TextView mTvDate;
        @BindView(R.id.tv_content)
        TextView mTvContent;

        public NewsViewHolder(Context context, @LayoutRes int resource) {
            super(context, resource);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        NotificationCenter.defaultCenter.removeListener(this);
    }
}
